package ru.sanluck.tg;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@AllArgsConstructor
public class DefaultTgUserService implements TgUserService {

    private final TgUserRepository tgUserRepository;
    private final TgUserMapper tgUserMapper;
    @Override
    @Transactional
    public TgUser createTgUser(TgUser user) {
        TgUserEntity tgUserEntity = tgUserMapper.toEntity(user);
        return tgUserMapper.toDomain(tgUserRepository.save(tgUserEntity));
    }

    @Override
    public List<TgUser> getUsers() {
        return new ArrayList<>();
    }

    @Override
    public TgUser getUser(String userName) {
        return tgUserRepository.findByUserName(userName)
                .map(tgUserMapper::toDomain)
                .orElse(null);
    }

    @Override
    @Transactional
    public TgUser changeDialog(String userName, Dialog dialog) {
        Optional<TgUserEntity> tgUserEntity = tgUserRepository.findByUserName(userName);

        if (tgUserEntity.isPresent()) {
            TgUserEntity entity = tgUserEntity.get();
            entity.setDialog(dialog);
            TgUserEntity changedDialog = tgUserRepository.save(entity);

            return tgUserMapper.toDomain(changedDialog);
        }

        return null;
    }
}
